package com.hspedu.socket.TCPFileUpload;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author DL5O
 * @version 1.0
 */
public class TCPFileUploadServer {
    public static void main(String[] args) throws Exception {
        String saveFilePath = "src\\bg.png";
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("等待客户端连接...");
        Socket accept = serverSocket.accept();
        System.out.println("客户端连接成功:" + accept.getInetAddress());

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveFilePath));
        BufferedInputStream bis= new BufferedInputStream(accept.getInputStream());
        //把管道中的bis取出然后写入到 bos这个输出流中对应的文件地址去
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        bos.write(bytes);

        bos.close();
        System.out.println("文件已成功写入！！");

        //向客户端发送成功写入的消息
        /*OutputStream outputStream = accept.getOutputStream();
        outputStream.write("服务端:已收到图片..".getBytes());
        outputStream.flush();*/

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
        bw.write("服务端:已收到图片..");
        bw.flush();
        accept.shutdownOutput();

        bw.close();
        bis.close();
        accept.close();
    }
}
